package com.naihe.anderson.sms.activity;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;

import com.naihe.anderson.sms.R;
import com.naihe.anderson.sms.application.NhSmsApp;
import com.naihe.anderson.sms.entity.ContactUser;
import com.naihe.anderson.sms.entity.Nhsms;
import com.naihe.anderson.sms.entity.SignatureMsg;
import com.naihe.anderson.sms.listener.OnCreateDataListener;
import com.naihe.anderson.sms.manager.ContactMgr;
import com.naihe.anderson.sms.manager.NhSmsMgr;
import com.naihe.anderson.sms.util.ObjectUtil;
import com.naihe.anderson.sms.widgets.AppPanel;

public class MakeNewMessageActivity extends Activity implements OnClickListener, OnCreateDataListener{

	public static final int REQUEST_MAKENEW_SIGNATURE_CODE = 13349;
	public static final int REQUEST_FRIENDCHECK_CODE = 10;
	
	AppPanel appPanel;
	Button makenewPlusFile;
	
	ImageButton makenewFriend;
	ImageButton makenewSend;
	EditText makenewForFriend;
	EditText makenewForBody;
	ProgressBar reloadingProgress;
	
	Button change_btn;
	Button back_btn;
	
	NhSmsApp nhSmsApp;
	ContactMgr contactMgr;
	NhSmsMgr nhSmsMgr;
	
	public static HashMap<String, Boolean> numberMap = new HashMap<String, Boolean>();
	private StringBuffer noContactNumbers = new StringBuffer();
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.new_message_layout);
        nhSmsApp = (NhSmsApp) getApplication();
        contactMgr = nhSmsApp.getContactMgr();
        nhSmsMgr = nhSmsApp.getNhSmsMgr();
        
        initView();
        
        Uri uri= getIntent().getData();
		if(uri != null)
		{
			numberMap.clear();
			String url = ObjectUtil.phoneNumberFormat(Uri.decode(uri.toString()).toString());
			
			String uriaddress = url.substring(url.indexOf(":")+1);
			ContactUser contactUser = null;
			Long contactId = contactMgr.getContactIdByPhoneNum(uriaddress);
			contactUser = contactMgr.getContactUserById(contactId);
			numberMap.put(uriaddress, true);
			if(contactUser != null){
				makenewForFriend.setText(contactUser.getName() + "<" + uriaddress + ">,");
				makenewForFriend.setSelection(makenewForFriend.getText().toString().length());
			} else {
				noContactNumbers.append(uriaddress + ",");
				makenewForFriend.setText(uriaddress + ",");
				makenewForFriend.setSelection(makenewForFriend.getText().toString().length());
			}
		}
    }
	
	public void initView(){
		reloadingProgress = (ProgressBar) findViewById(R.id.reloading_progress);
		
		change_btn = (Button) findViewById(R.id.change_btn);
		change_btn.setOnClickListener(this);

		back_btn = (Button) findViewById(R.id.back_btn);
		back_btn.setOnClickListener(this);
		
		appPanel = (AppPanel) findViewById(R.id.makenew_appPanel);
		makenewPlusFile = (Button) findViewById(R.id.makenew_plus_file);
		makenewPlusFile.setOnClickListener(this);
		
		makenewForBody = (EditText) findViewById(R.id.makenew_forbody);
		makenewForFriend = (EditText) findViewById(R.id.makenew_for_friend);
		makenewForFriend.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
            	if(appPanel.isShown())
    				appPanel.setVisibility(View.GONE);
                return false;
            }
        });
		makenewForBody.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
            	if(appPanel.isShown())
    				appPanel.setVisibility(View.GONE);
                return false;
            }
        });
		
		makenewFriend = (ImageButton) findViewById(R.id.makenew_friend);
		makenewFriend.setOnClickListener(this);
		
		makenewSend = (ImageButton) findViewById(R.id.makenew_send);
		makenewSend.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v.getId() == R.id.makenew_friend){
			Intent intent = new Intent(MakeNewMessageActivity.this, FriendCheckActivity.class);
			startActivityForResult(intent, REQUEST_FRIENDCHECK_CODE);
		} else if(v.getId() == R.id.makenew_send){
			if(makenewForBody.getText().toString().length() > 0){
				reloadingProgress.setVisibility(View.VISIBLE);
				makenewSend.setClickable(false);
				hiddenImm(v);
				sendSms();
			}
		} else if(v.getId() == R.id.makenew_plus_file){
			if(appPanel.isShown()){
				appPanel.setVisibility(View.GONE);
			} else {
				appPanel.setVisibility(View.VISIBLE);
				hiddenImm(v);
			}
		}else if(v.getId() == R.id.back_btn){
			numberMap.clear();
			finish();
			System.gc();
		} else if(v.getId() == R.id.change_btn){
			Intent intent = new Intent(MakeNewMessageActivity.this, MakeNewSignatureActivity.class);
			intent.putExtra("makenewForFriend", makenewForFriend.getText().toString());
			intent.putExtra("makenewForBody", makenewForBody.getText().toString());
			startActivityForResult(intent, REQUEST_MAKENEW_SIGNATURE_CODE);
			System.gc();
		}
	}

	/**
     * 隐藏输入法
     *
     * @param view
     */
    private void hiddenImm(View view) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }
    
	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 截获按键事件
        if(KeyEvent.KEYCODE_BACK == keyCode){
        	if(appPanel.isShown()){
        		appPanel.setVisibility(View.GONE);
        		return true;
        	}
        	System.gc();
        	return super.onKeyDown(keyCode, event);
		}

        return super.onKeyDown(keyCode, event);
    }
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(data == null || data.getExtras() == null)
			return;
		if(requestCode == REQUEST_FRIENDCHECK_CODE && resultCode == RESULT_OK){
			String backString = data.getStringExtra("backString");
			makenewForFriend.setText(noContactNumbers.toString() + backString);
			makenewForFriend.setSelection(makenewForFriend.getText().toString().length());
		} else if (requestCode == REQUEST_MAKENEW_SIGNATURE_CODE && resultCode == RESULT_OK) {
			SignatureMsg signatureMsg = (SignatureMsg) data.getExtras().get("SignatureMsg");
			nhSmsApp.getSignatureMsgMgr().saveSignatureMsgInfo(signatureMsg);
			
			Intent intent = new Intent(MakeNewMessageActivity.this, SignatureMsgActivity.class);
			startActivity(intent);
			numberMap.clear();
			finish();
			System.gc();
		}
	}
	
	private void sendSms() {
		
		String smsBody = makenewForBody.getText().toString();
        String smsAddress =   makenewForFriend.getText().toString();
        String[] smsAddresseArray = smsAddress.split(",");
        
        List<Nhsms> nhsmsList = new ArrayList<Nhsms>();
        
        for (int i = 0; i < smsAddresseArray.length; i++) {
        	String addressTemp  = smsAddresseArray[i];
        	if(addressTemp.contains("<") && addressTemp.contains(">")){
        		addressTemp = addressTemp.substring(addressTemp.indexOf("<")+1, addressTemp.indexOf(">"));
        	}
        	
        	Date date = new Date();
        	Nhsms nhsms = new Nhsms();
			nhsms.setAddress(addressTemp);
			nhsms.setBody(smsBody);
			nhsms.setDate(date.getTime());
			nhsms.setDate_sent(date.getTime());
			nhsms.setError_code(0);
			nhsms.setLocked(0);
			nhsms.setProtocol(0);
			nhsms.setRead(1);
			nhsms.setReply_path_present(0);
			nhsms.setSeen(1);
			nhsms.setService_center("");
			nhsms.setStatus(Nhsms.STATUS_PENDING);
			nhsms.setSubject("");
			nhsms.setThread_id(-1);
			nhsms.setType(Nhsms.MESSAGE_TYPE_SENT);
			
			ContactUser contactUser = contactMgr.getContactUserById(contactMgr.getContactIdByPhoneNum(addressTemp));
			if(contactUser != null){
				nhsms.setPerson(contactUser.getContactId());
			} else {
				nhsms.setPerson(0);
			}
			
			nhsmsList.add(nhsms);
        }
        
        nhSmsMgr.sendSms(nhsmsList, this);
        
        smsAddresseArray = null;
	}
	
	public static final int MSG_WHAT_FINISH_ACTIVITY = 0;
	Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_WHAT_FINISH_ACTIVITY:
				reloadingProgress.setVisibility(View.GONE);
				numberMap.clear();
				MakeNewMessageActivity.this.finish();
				break;
			default:
				break;
			}
		}
	};

	@Override
	public void OnCreateData() {
		mHandler.sendEmptyMessage(MSG_WHAT_FINISH_ACTIVITY);
        System.gc();
	}
}
